package com.shop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.shop.bean.Goods;
import com.shop.dao.BaseDao;
import com.shop.dao.GoodsDao;

public class GoodsDaoImpl implements GoodsDao {
	public List<Goods> queryByPageNS(int pageNum,int pageSize) {
		Connection conn = BaseDao.getConn();// 打开连接
		String sql = "SELECT * FROM goods LIMIT ?,?";
		List<Goods> list = new ArrayList<Goods>();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, (pageNum - 1) * pageSize);
			ps.setInt(2, pageSize);
			rs = ps.executeQuery();
			while (rs.next()) {
				Goods g = new Goods();
				g.setId(rs.getInt("id"));
				g.setGoodsName(rs.getString("goodsName"));
				g.setGoodsFactory(rs.getString("goodsFactory"));
				g.setGoodsType(rs.getString("goodsType"));
				g.setGoodsPrice(rs.getDouble("goodsPrice"));
				g.setGoodsNum(rs.getInt("goodsNum"));
				list.add(g);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return list;
	}
	
	public int queryCount() {
		Connection conn = BaseDao.getConn();// 打开连接
		String sql = "SELECT COUNT(1) AS num FROM goods";
		PreparedStatement ps = null;
		int num = 0;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if(rs.next()) {
				num = rs.getInt("num");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return num;
	}

	public int deleteGoodsById(int id) {
		Object[] param = {id};
		String sql = "DELETE FROM goods WHERE id = ?";
		return BaseDao.executeUpdate(sql,param);
	}
}
